'use strict';

const Controller = require('egg').Controller;

class ConfigController extends Controller {
  async index() {
    const {ctx} = this;
    let option = ctx.helper.formatOptions(ctx.query,["configName","configKey","configType"]);
    try {
      let result = await ctx.model.SysConfig.findAndCountAll(option);
      ctx.body = ctx.helper.formateResponseList(result);
    } catch (error) {
      ctx.body = ctx.helper.formateResponse(null,"查询失败",310)
    }
  }
  async show(){
    const {ctx} = this;
    const {id} = ctx.params;
    let configId = Number(id);
    if(configId){
      const result = await ctx.model.SysConfig.findByPk(id);
      ctx.body = ctx.helper.formateResponse(result);
    }else{
      ctx.body = ctx.helper.formateResponse(null,500,'查询失败');
    }
  }
  async create(){
    const {ctx} = this;
    const data = ctx.request.body;
    const user = ctx.session.userinfo;
    const configData = {
      configKey:data.configKey,
      configName:data.configName,
      configType:data.configType,
      configValue:data.configValue,
      remark:data.remark,
      createBy:user.userName,
      updateBy:user.userName
    };
    await ctx.model.SysConfig.create(configData);
    ctx.body = ctx.helper.formateResponse(null);
  }
  async update(){
    const {ctx} = this;
    const data = ctx.request.body;
    const currentConfig = await ctx.model.SysConfig.findByPk(Number(data.configId));
    const user = ctx.session.userinfo;
    await currentConfig.update({
      configKey:data.configKey,
      configName:data.configName,
      configType:data.configType,
      configValue:data.configValue,
      remark:data.remark,
      updateBy:user.userName
    });
    ctx.body = ctx.helper.formateResponse(null);
  }
  async destroy(){
    const {ctx} = this;
    const {id} = ctx.params;
    const config = await ctx.model.SysConfig.findByPk(Number(id));
    await config.destroy();
    ctx.body = ctx.helper.formateResponse(null);
  }
  async getConfigByKey(){
    const {ctx} = this;
    const {key} = ctx.params;
    const config = await ctx.model.SysConfig.findOne({
      where:{
        configKey:key
      }
    });
    
    ctx.body = ctx.helper.formateResponse(null,200,config.configValue);
  }
}

module.exports = ConfigController;
